<template>
  <div :style="{height:props.chartHeight}" ref="chart" class="chart"></div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, markRaw, watch } from 'vue';
import * as echarts from 'echarts/core';
import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DatasetComponent,
    TransformComponent,
    LegendComponent
} from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DatasetComponent,
    TransformComponent,
    LegendComponent,
    LineChart,
    CanvasRenderer,
    LabelLayout,
    UniversalTransition
])

const chart = ref<HTMLDivElement>()
const myChart = ref<any>()
const props = defineProps(['data', 'chartHeight'])
const xAxisD = ref<string[]>([])
const seriesD = ref<number[]>([])

const visit = (e: any) => {
    xAxisD.value = [];
    seriesD.value = [];
    if (!e || !Array.isArray(e)) return;
    
    for (let i = 0; i < e.length; i++) {
        xAxisD.value.push(e[i].date);
        seriesD.value.push(e[i].count);
    }
}

const getOption = () => ({
    color: ['#2B5AED'],
    grid: {
        top: "4%",
        left: "0%",
        right: "0%",
        bottom: "0%",
        containLabel: true,
    },
    xAxis: {
        type: 'category',
        data: xAxisD.value,
    },
    yAxis: {
        type: 'value'
    },
    series: [
        {
            data: seriesD.value,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 5,
            showSymbol: true,
        }
    ]
})

// 初始化图表
const initChart = () => {
    if (!chart.value) return
    
    // 如果已存在实例，先销毁
    if (myChart.value) {
        myChart.value.dispose()
    }
    
    myChart.value = markRaw(echarts.init(chart.value))
    const resizeHandler = () => myChart.value?.resize()
    
    window.addEventListener('resize', resizeHandler)
    myChart.value._resizeHandler = resizeHandler
    
    return myChart.value
}

// 更新图表
const updateChart = () => {
    if (!myChart.value) {
        myChart.value = initChart()
    }
    
    if (myChart.value) {
        myChart.value.setOption(getOption())
    }
}

onMounted(() => {
    visit(props.data)
    updateChart()
})

watch(
    () => props.data,
    (newData) => {
        visit(newData)
        updateChart()
    },
    { deep: true }
)

onBeforeUnmount(() => {
    if (myChart.value) {
        if (myChart.value._resizeHandler) {
            window.removeEventListener('resize', myChart.value._resizeHandler)
        }
        myChart.value.dispose()
        myChart.value = null
    }
})
</script>
<style scoped lang="less">
.chart {
    width: 100%;
}
</style>
